package com.zw.weiyi.fragment;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.zw.weiyi.avtivity.AddPerson;
import com.zw.weiyi.avtivity.InfoActivity;
import com.zw.weiyi.enety.Person;
import com.zw.weiyi.phonesms.R;
import com.zw.weiyi.util.CharacterParser;
import com.zw.weiyi.util.PYComparator;
import com.zw.weiyi.view.ClearEditText;
import com.zw.weiyi.view.SideBar;
import com.zw.weiyi.view.SideBar.OnTouchingLetterChangedListener;

/**
 * 联系人列表  
 * @author Striver_zw
 *  Date 2014-11-24
 */
@SuppressLint("ValidFragment")
public class InfoFragment extends Fragment {
	private View view;// 缓存页面
	public ListView perListView;
	public personAdapter pAdapter;

	private ClearEditText mClearEditText;//查询联系人
	private SideBar sideBar;
	private TextView dialog;
	private TextView sizes;// 联系人个数
	private Cursor cursor;

	private Context context;
	private ContentResolver resolver;

	private ImageButton im_add;// 添加联系人

	public int personSize;
	public List<Person> personsList;

	/**
	 *  查询条件
	 *  Photo.PHOTO_ID 头像查询
	 */
	public final static String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PYComparator pyComparator;

	@SuppressLint("ValidFragment")
	public InfoFragment(Context context) {
		this.context = context;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.info_fragment, container, false);
		}
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);// 先移除
		}
		// 初始化
		initview(view);
		return view;
	}

	// 初始化
	public void initview(View view) {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pyComparator = new PYComparator();

		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sizes = (TextView) view.findViewById(R.id.sizes);
		im_add = (ImageButton) view.findViewById(R.id.im_add);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = pAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					perListView.setSelection(position);
				}
			}
		});

		personsList = new ArrayList<Person>();
		perListView = (ListView) view.findViewById(R.id.personList);
		im_add = (ImageButton) view.findViewById(R.id.im_add);
		im_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//点击条目添加联系人
				context.startActivity(new Intent(context, AddPerson.class));

			}
		});

		// 条目监听器
		perListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				Intent intent = new Intent(context, InfoActivity.class);
				// 通过意图发送号码
				Person person = new Person();
				intent.putExtra("name",
						((Person) pAdapter.getItem(position)).getName());
				intent.putExtra("id",
						((Person) pAdapter.getItem(position)).getId());
				intent.putExtra("phoneNumber",
						((Person) pAdapter.getItem(position)).getPhoneNumber());
				intent.putExtra("iconid",
						((Person) pAdapter.getItem(position)).getIconId());
				context.startActivity(intent);
			}
		});

		personsList = filledData(initContacts());
		sizes.setText(personsList.size() + " 位联系人");

		// 根据a-z进行排序源数据
		Collections.sort(personsList, pyComparator);
		pAdapter = new personAdapter(context, personsList);
		perListView.setAdapter(pAdapter);

		mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}

		});
	}

	/**
	 * 为ListView填充数据 
	 * @param date
	 * @return
	 */
	private List<Person> filledData(List<Person> p) {
		List<Person> mSortList = new ArrayList<Person>();

		for (int i = 0; i < p.size(); i++) {
			Person person = new Person();
			person.setName(p.get(i).getName());
			person.setPhoneNumber(p.get(i).getPhoneNumber());
			person.setIconId(p.get(i).getIconId());
			person.setIcon(p.get(i).getIcon());
			person.setId(p.get(i).getId());
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(p.get(i).getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				person.setSortLetters(sortString.toUpperCase());
			} else {
				person.setSortLetters("#");
			}
			mSortList.add(person);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<Person> filterDateList = new ArrayList<Person>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = personsList;
		} else {
			filterDateList.clear();
			for (Person person : personsList) {
				String name = person.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(person);
				}
			}
		}
		// 根据a-z进行排序
		Collections.sort(filterDateList, pyComparator);

		pAdapter.updateListView(filterDateList);
	}

	// 得到联系人的数据
	public List<Person> initContacts() {
		resolver = context.getContentResolver();
		cursor = context.getContentResolver().query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);
		personSize = cursor.getCount();
		pAdapter = new personAdapter(context, personsList);

		Person person = null;
		if (cursor != null) {
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					.moveToNext()) {
				person = new Person();
				person.setName(cursor.getString(0));
				person.setPhoneNumber(cursor.getString(1));
				// 头像id
				person.setIconId(cursor.getLong(2));
				// 联系人id
				person.setId(cursor.getLong(3));

				if (cursor.getLong(2) > 0) { // 头像默认为0
					Uri uri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI,
							person.getId());
					InputStream input = ContactsContract.Contacts
							.openContactPhotoInputStream(resolver, uri);
					person.setIcon(BitmapFactory.decodeStream(input));

				} else {// 没有则默认
					person.setIcon(BitmapFactory.decodeResource(getResources(),
							R.drawable.ic_launcher));
				}
				personsList.add(person);
			}
		}
		cursor.close();
		return personsList;

	}

	class ViewHolder {
		private TextView personnumber;
		private TextView personName;
		private ImageView person_icon;
		TextView tvLetter;

		public ViewHolder(View view) {
			personnumber = (TextView) view.findViewById(R.id.person_number);
			personName = (TextView) view.findViewById(R.id.person_name);
			person_icon = (ImageView) view.findViewById(R.id.person_icon);
			tvLetter = (TextView) view.findViewById(R.id.catalog);
			view.setTag(this);
		}
	}

	// 适配器
	class personAdapter extends BaseAdapter implements SectionIndexer {
		private List<Person> list = null;
		private Context mContext;

		public personAdapter(Context mContext, List<Person> list) {
			this.mContext = mContext;
			this.list = list;
		}

		/**
		 * 当ListView数据发生变化时,调用此方法来更新ListView 
		 * @param list
		 */
		public void updateListView(List<Person> list) {
			this.list = list;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				convertView = View.inflate(getActivity()
						.getApplicationContext(),
						R.layout.info_person_list_item, null);
				new ViewHolder(convertView);
			}

			ViewHolder holder = (ViewHolder) convertView.getTag();
			Person person = list.get(position);
			holder.personName.setText(person.getName());
			holder.personnumber.setText(person.getPhoneNumber());
			holder.person_icon.setImageBitmap(person.getIcon());
			// 根据position获取分类的首字母的Char ascii值
			int section = getSectionForPosition(position);

			// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
			if (position == getPositionForSection(section)) {
				holder.tvLetter.setVisibility(View.VISIBLE);
				holder.tvLetter.setText(person.getSortLetters());
			} else {
				holder.tvLetter.setVisibility(View.GONE);
			}
			return convertView;
		}

		/**
		 * 根据ListView的当前位置获取分类的首字母的Char ascii值
		 */
		public int getSectionForPosition(int position) {
			return list.get(position).getSortLetters().charAt(0);
		}

		/**
		 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < getCount(); i++) {
				String sortStr = list.get(i).getSortLetters();
				char firstChar = sortStr.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}
			return -1;
		}

		/**
		 * 提取英文的首字母，非英文字母用#代替。
		 * 
		 * @param str
		 * @return
		 */
		private String getAlpha(String str) {
			String sortStr = str.trim().substring(0, 1).toUpperCase();
			// 正则表达式，判断首字母是否是英文字母
			if (sortStr.matches("[A-Z]")) {
				return sortStr;
			} else {
				return "#";
			}
		}

		@Override
		public Object[] getSections() {
			return null;
		}
	}
}